package com.edu.etu.gui.checkit;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

public class EdiListActivity extends ActionBarActivity implements View.OnClickListener{
    LinearLayout llMain;
    LinearLayout TemplateElements;
    LinearLayout menuTemplate;
    ImageButton btnAddElement;
    ImageButton btnSave;

    EditText element;

    TextView NameList;

    SQLiteHelperList openHelperList;
    SQLiteDatabase db;
    ContentValues cv;
    long rowIdEl=0;

    Integer idElement;
    Integer idTemplate;
    Integer idAddTemplate;
    EditText input;

    CheckBox element_checkbox;
    private HashMap<View,Integer> mapViewElement = new HashMap<View,Integer>();
    private HashMap<View,Integer> mapViewTemplate = new HashMap<View,Integer>();
    private HashMap<View,Integer> mapAddTemplate = new HashMap<View,Integer>();
    SharedPreferences sPref;
    final String LOAD_VIEW = "viewlist";
    String savedText;
    int currentListid=0;
    Cursor cursor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_list);

        btnAddElement=(ImageButton) findViewById(R.id.btnAddElem);
        btnAddElement.setOnClickListener(this);

        btnSave=(ImageButton) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);

        TemplateElements = (LinearLayout) findViewById(R.id.TemplateElements);
        NameList = (TextView) findViewById(R.id.NameList);
        element = (EditText) findViewById(R.id.Element);
        llMain = (LinearLayout) findViewById(R.id.llMain);
        menuTemplate = (LinearLayout) findViewById(R.id.menuTemplate);

        openHelperList = new SQLiteHelperList(getApplicationContext());
        db = openHelperList.getWritableDatabase();
        cv = new ContentValues();

        cursor = db.query("Lists", null, null, null, null, null, null);
        if(cursor.moveToFirst())
        {
            do {
                if(cursor.getInt(cursor.getColumnIndex("_id"))==getIntent().getIntExtra("ListId",-1))
                {
                    NameList.setText(cursor.getString(cursor.getColumnIndex("nameLists")));
                    currentListid = getIntent().getIntExtra("ListId",-1);
                }
            }
            while (cursor.moveToNext());
        }
        cursor.close();

        draw_list();

        Cursor cList = db.query("ListsTemplates", null, null, null, null, null, null);
        if (cList.moveToFirst()) {

            do {
                LayoutInflater inflater = getLayoutInflater();
                View main_list_element = inflater.inflate(R.layout.view_add_template,null,false);
                Button open_list_button = (Button)main_list_element.findViewById(R.id.add_template);


                mapViewTemplate.put(open_list_button, cList.getInt(cList.getColumnIndex("_id4")));

                open_list_button.setOnClickListener(this);
                open_list_button.setText(cList.getString(cList.getColumnIndex("nameListsTemplates")));
                menuTemplate.addView(main_list_element);
            }
            while (cList.moveToNext());
        }
        cList.close();

        sPref = getPreferences(MODE_PRIVATE);
        savedText = sPref.getString(LOAD_VIEW,"");
        if(savedText=="")
        {
            Toast toast =Toast.makeText(getApplicationContext(),getString(R.string.message2), Toast.LENGTH_LONG);
            toast.show();
        }
    }


    public void draw_list()
    {
        llMain.removeAllViews();
        mapViewElement.clear();
        cursor = db.query("Elements", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            int idList = cursor.getColumnIndex("idList");
            int nameElements = cursor.getColumnIndex("nameElements");
            int boolElements = cursor.getColumnIndex("boolElements");
            int idElement = cursor.getColumnIndex("_id2");
            do {
                if(getIntent().getIntExtra("ListId",-1)==cursor.getInt(idList))
                {
                    LayoutInflater inflater = getLayoutInflater();
                    View list_element = inflater.inflate(R.layout.list_element_template,null,false);
                    CheckBox element_checkbox =  (CheckBox)list_element.findViewById(R.id.list_element_checkbox);
                    element_checkbox.setText(cursor.getString(nameElements));
                    element_checkbox.setChecked(cursor.getInt(boolElements)==1);
                    element_checkbox.setOnClickListener(this);
                    ImageButton imgButtonDelete = (ImageButton) list_element.findViewById(R.id.btnDeleteListElement);
                    imgButtonDelete.setOnClickListener(this);
                    ImageButton imgButtonFix = (ImageButton) list_element.findViewById(R.id.btnFix);
                    imgButtonFix.setOnClickListener(this);
                    llMain.addView(list_element);
                    mapViewElement.put(element_checkbox,cursor.getInt(idElement));
                    mapViewElement.put(imgButtonDelete, cursor.getInt(idElement));
                    mapViewElement.put(imgButtonFix, cursor.getInt(idElement));
                }
            }
            while (cursor.moveToNext());
        }
        cursor.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.new_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        idElement=mapViewElement.get(v);
        if(idElement!=null)
        {
            switch (v.getId())
            {
                case R.id.btnDeleteListElement:
                    ImageButton ib = (ImageButton)v;
                    LinearLayout ll = (LinearLayout)ib.getParent();
                    ll.setVisibility(View.GONE);
                    cursor = db.query("Elements", null, null, null, null, null, null);
                    if (cursor.moveToFirst()) {
                        do {
                            if(idElement==cursor.getInt(cursor.getColumnIndex("_id2")))
                            {
                                String i = cursor.getString(cursor.getColumnIndex("_id2"));
                                if (i.equalsIgnoreCase("")) {
                                    break;
                                }
                                db.execSQL("delete from Elements where _id2='"+i+"'");

                            }
                        }
                        while (cursor.moveToNext());
                    }
                    cursor.close();
                    break;
                case R.id.btnFix:
                    AlertDialog.Builder adb = new AlertDialog.Builder(this);
                    input = new EditText(this);
                    cursor = db.query("Elements", null, null, null, null, null, null);
                    if (cursor.moveToFirst()) {
                        do {
                            if(idElement==cursor.getInt(cursor.getColumnIndex("_id2")))
                            {
                                input.setText(cursor.getString(cursor.getColumnIndex("nameElements")));
                            }
                        }
                        while (cursor.moveToNext());
                    }
                    cursor.close();
                    adb.setTitle(getString(R.string.EditingElement));
                    adb.setView(input);
                    adb.setNegativeButton(R.string.no, myClickListener);
                    adb.setPositiveButton(R.string.yes, myClickListener);
                    adb.show();
                    break;
            }
        }

        idTemplate=mapViewTemplate.get(v);
        if(idTemplate!=null)
        {
            switch (v.getId())
            {
                case R.id.add_template:
                    cursor = db.query("Template", null, null, null, null, null, null);
                    TemplateElements.removeAllViews();
                    if (cursor.moveToFirst()) {
                        int ListsTemplates = cursor.getColumnIndex("ListsTemplates");
                        int nameElementsTemplate = cursor.getColumnIndex("nameElementsTemplate");
                        int boolTemplate = cursor.getColumnIndex("boolTemplate");
                        int idElement = cursor.getColumnIndex("_id3");
                        do {
                            if(mapViewTemplate.get(v)==cursor.getInt(ListsTemplates))
                            {

                                LayoutInflater inflater = getLayoutInflater();
                                View list_element = inflater.inflate(R.layout.add_template_element,null,false);
                                TextView templateElementName = (TextView)list_element.findViewById(R.id.textNameTemplateElement);
                                templateElementName.setText(cursor.getString(nameElementsTemplate));
                                ImageButton addTemplateElement = (ImageButton)list_element.findViewById(R.id.imgBtnAddTemplateElemet);
                                addTemplateElement.setOnClickListener(this);
                                mapAddTemplate.put(addTemplateElement,cursor.getInt(idElement));
                                TemplateElements.addView(list_element);
                            }
                        }
                        while (cursor.moveToNext());
                    }
                    cursor.close();
                    if(savedText=="")
                    {
                        Toast toast =Toast.makeText(getApplicationContext(),getString(R.string.message3), Toast.LENGTH_LONG);
                        toast.show();
                        SharedPreferences.Editor ed = sPref.edit();
                        ed.putString(LOAD_VIEW, "check");
                        ed.commit();
                    }
                    break;
            }
        }
        idAddTemplate=mapAddTemplate.get(v);
        if(idAddTemplate!=null)
        {
            switch (v.getId())
            {
                case R.id.imgBtnAddTemplateElemet:
                    cursor = db.query("Template",null,null,null,null,null,null);
                    if (cursor.moveToFirst()) {
                        int ListsTemplates = cursor.getColumnIndex("ListsTemplates");
                        int nameElementsTemplate = cursor.getColumnIndex("nameElementsTemplate");
                        int boolTemplate = cursor.getColumnIndex("boolTemplate");
                        int idElement = cursor.getColumnIndex("_id3");
                        do {
                            if(cursor.getInt(idElement)==idAddTemplate)
                            {
                                ContentValues tempCV= new ContentValues();
                                tempCV.put(openHelperList.nameElements,cursor.getString(nameElementsTemplate));
                                tempCV.put(openHelperList.idList,currentListid);
                                tempCV.put(openHelperList.boolElements,0);
                                int tempId =(int)db.insert(openHelperList.NameTableElements,null,tempCV);

                                LayoutInflater inflater = getLayoutInflater();
                                View list_element = inflater.inflate(R.layout.list_element_template,null,false);
                                element_checkbox =  (CheckBox)list_element.findViewById(R.id.list_element_checkbox);
                                element_checkbox.setText(cursor.getString(nameElementsTemplate));
                                ImageButton imgButtonDelete = (ImageButton) list_element.findViewById(R.id.btnDeleteListElement);
                                ImageButton imgButtonFix = (ImageButton) list_element.findViewById(R.id.btnFix);
                                llMain.addView(list_element);
                                element_checkbox.setOnClickListener(this);
                                imgButtonDelete.setOnClickListener(this);
                                imgButtonFix.setOnClickListener(this);
                                element.setText(null);
                                mapViewElement.put(element_checkbox,tempId);
                                mapViewElement.put(imgButtonFix,tempId);
                                mapViewElement.put(imgButtonDelete,tempId);
                            }
                        }
                        while (cursor.moveToNext());
                    }
                    cursor.close();

                    break;
            }
        }
        switch (v.getId())
        {
            case R.id.btnAddElem:
                LayoutInflater inflater = getLayoutInflater();
                View list_element = inflater.inflate(R.layout.list_element_template,null,false);
                element_checkbox =  (CheckBox)list_element.findViewById(R.id.list_element_checkbox);
                if(element.length()==0)element.setText("Element");
                element_checkbox.setText(element.getText().toString());
                ImageButton imgButtonDelete = (ImageButton) list_element.findViewById(R.id.btnDeleteListElement);
                ImageButton imgButtonFix = (ImageButton) list_element.findViewById(R.id.btnFix);
                llMain.addView(list_element);
                element_checkbox.setOnClickListener(this);
                imgButtonDelete.setOnClickListener(this);
                imgButtonFix.setOnClickListener(this);

                cv.put(openHelperList.idList, currentListid);
                cv.put(openHelperList.nameElements, element.getText().toString());
                cv.put(openHelperList.boolElements, 0);
                rowIdEl = db.insert(openHelperList.NameTableElements,null,cv);
                element.setText(null);
                cursor = db.query("Elements", null, null, null, null, null, null);
                if (cursor.moveToLast()) {
                    int _id2 = cursor.getColumnIndex("_id2");
                    mapViewElement.put(element_checkbox, cursor.getInt(_id2));
                    mapViewElement.put(imgButtonDelete, cursor.getInt(_id2));
                    mapViewElement.put(imgButtonFix, cursor.getInt(_id2));
                }
                cursor.close();
                if(savedText.equals(""))
                {
                    Toast toast =Toast.makeText(getApplicationContext(),getString(R.string.message4), Toast.LENGTH_LONG);
                    toast.show();
                }

                break;

            case R.id.btnSave:
                startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
        }

    }



    DialogInterface.OnClickListener myClickListener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case Dialog.BUTTON_POSITIVE:
                    cursor = db.query("Elements", null, null, null, null, null, null);
                    if (cursor.moveToFirst()) {
                        do {
                            if(idElement==cursor.getInt(cursor.getColumnIndex("_id2")))
                            {
                                String strFilter = "_id2="+idElement;
                                ContentValues args = new ContentValues();
                                args.put(openHelperList.nameElements,input.getText().toString());
                                db.update(openHelperList.NameTableElements,args,strFilter,null);
                                finish();
                                startActivity(getIntent());
                            }
                        }
                        while (cursor.moveToNext());
                    }
                    cursor.close();
                    break;
                case Dialog.BUTTON_NEGATIVE:

                    break;
            }

        }

    };
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        draw_list();

    }
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        draw_list();

    }

}
